/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.xcxAdmin.appweb;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.cache.JedisUtils;
import com.jeesite.common.responseReturn.entity.ResultObject;
import com.jeesite.common.responseReturn.utils.CommonUtils;
import com.jeesite.common.responseReturn.web.Render;
import com.jeesite.common.utils.CommonPath;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.config.MyProps;
import com.jeesite.modules.config.OpenidUtils;
import com.jeesite.modules.goods.entity.*;
import com.jeesite.modules.goods.service.*;
import com.jeesite.modules.jdProduct.utils.ProductPoolUtils;
import com.jeesite.modules.pay.totalPay.util.StringUtil;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.xcxAdmin.entity.SmsInfo;
import com.jeesite.modules.xcxAdmin.entity.ZtAdmin;
import com.jeesite.modules.xcxAdmin.entity.ZtWithdraw;
import com.jeesite.modules.xcxAdmin.service.FlexIdentService;
import com.jeesite.modules.xcxAdmin.service.SmsSendService;
import com.jeesite.modules.xcxAdmin.service.ZtAdminService;
import com.jeesite.modules.xcxAdmin.service.ZtWithdrawService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 测试数据Controller
 * 
 * @author ThinkGem
 * @version 2018-04-22
 */
@Controller
@RequestMapping(value = "${frontPath}/ztAdmin")
public class AppZtAdminController extends BaseController {

	@Autowired
	private MyProps myProps;
	@Autowired
	private ZtAdminService ztAdminService;
	@Autowired
	private UserService userService;
	private SmsSendService smsSendService;
	@Autowired
	private ZtFinancialService ztFinancialService;

	@Autowired
	private FlexIdentService flexIdentService;
	@Autowired
	private ZtCardMemService ztCardMemService;
	
	@Autowired ZtCompanyService ztCompanyService;
	
	@Autowired
	ZtGoodsquanService ztGoodsquanService;
	@Autowired
	ZtGoodsService ztGoodsService;
	@Autowired
	ZtQuanselfService ztQuanselfService;

	@Autowired
	ZtWithdrawService ztWithdrawService;
	@Autowired
	ZtCardService ztCardService;
	/**
	 * 登录
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@ResponseBody
	@RequestMapping(value = "login")
	public void login(HttpServletRequest request, HttpServletResponse response,
			Model model) {

		String paramStr = CommonUtils.getParams(request);

		JSONObject jo = JSONObject.parseObject(paramStr);

		
		ResultObject res = new ResultObject();

		ZtAdmin smAdmin = new ZtAdmin();
		
		String username = "";
		if(jo.get("username")!=null){
			username=jo.get("username").toString();
		}
		
		String company = "0";
		if(jo.get("company")!=null&&!jo.get("company").equals("")){
			company=jo.get("company").toString();
		}
		
		
		String openid = jo.getString("openid");
		

		try {
			openid = OpenidUtils.getOpenId(openid).get("openid").toString();
		} catch (Exception ex) {
			ex.printStackTrace();
			
			ex.printStackTrace();
			res.setResult(400L);
			res.setMsg("login fail");
			
			Render.renderString(response, res);
			return;

		}
		
		String sex = "";
		if(jo.get("sex")!=null){
			sex=jo.get("sex").toString();
		}
		
		String headimgurl ="";
		if(jo.get("headimgurl")!=null){
			headimgurl=jo.get("headimgurl").toString();
		}
		
		smAdmin.setOpenid(openid);
		Date da = new Date();
		try {
			smAdmin = ztAdminService.getByOpenid(smAdmin);
			
			
			if (smAdmin == null) {
				
				if(StringUtils.isBlank(username)){
					res.setResult(400L);
					res.setMsg("login fail");
					Render.renderString(response, res);
					return;
				}
				
				smAdmin = new ZtAdmin();
				smAdmin.setOpenid(openid);
				smAdmin.setName(username);
				smAdmin.setUsername(username);
				smAdmin.setSex(sex);
				smAdmin.setHeadimgurl(headimgurl);
				smAdmin.setFirstDate(da);
				smAdmin.setCreateDate(da);
				smAdmin.setEndDate(da);
				smAdmin.setLevel("0");
				smAdmin.setMemtype("0");
				smAdmin.setCompany(company);
				
				
				Date date2 = new Date(System.currentTimeMillis());
				String str = String.format("%tj",date2);//得到time日期是在这年的第几天
				
				int s=ztAdminService.getCount()+1;
				
				String u=String.format("%06d", s);
				smAdmin.setBid(str+u);
				
				ztAdminService.setNames();
				ztAdminService.save(smAdmin);
				
			}else{
				smAdmin.setEndDate(da);
				if(!company.equals("0")){
					smAdmin.setEndDate(da);
					smAdmin.setCompany(company);
					ztAdminService.setNames();
					ztAdminService.save(smAdmin);
				}
			}
		} catch (Exception ex) {
			res.setResult(400L);
			res.setMsg("login fail");
			ex.printStackTrace();
			Render.renderString(response, res);
			return;
		}

		if(!smAdmin.getCompany().equals(null)&&!"0".equals(smAdmin.getCompany())){
			ZtCompany ztCompany=new ZtCompany();
			ztCompany.setCompany(smAdmin.getCompany());
			ztCompany=ztCompanyService.get(ztCompany);
			if(ztCompany!=null){

				smAdmin.setCompany(ztCompany.getCompany());
				smAdmin.setCompanyName(ztCompany.getCompanyname());
			}
		}
		res.setResult(200L);
		res.setData(smAdmin);
		Render.renderString(response, res);
	}
	/**
	 * 上传收款码
	 * @param request
	 * @param response
	 * @param model
	 */
	@ResponseBody
	@RequestMapping(value = "setPaycode")
	public void setPaycode(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String paramStr = CommonUtils.getParams(request);

		JSONObject jo = JSONObject.parseObject(paramStr);
		
		ResultObject res = new ResultObject();

		ZtAdmin smAdmin = new ZtAdmin();
		
		String adminid = jo.getString("adminid");
		String paycode = jo.getString("paycode");
		
		smAdmin.setId(adminid);
		smAdmin=ztAdminService.get(smAdmin);
		smAdmin.setPaycode(paycode);
		ztAdminService.setNames();
		ztAdminService.save(smAdmin);
		res.setResult(200L);
		res.setData(smAdmin);
		Render.renderString(response, res);
	}
	
	/**
	 * 上传微信二维码
	 * @param request
	 * @param response
	 * @param model
	 */
	@ResponseBody
	@RequestMapping(value = "getRate")
	public void getRate(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		//佣金    粉丝   下级掌柜  进度
		String paramStr = CommonUtils.getParams(request);

		JSONObject jo = JSONObject.parseObject(paramStr);
		
		ResultObject res = new ResultObject();
		ZtAdmin smAdmin = new ZtAdmin();
		String adminid = jo.getString("adminid");
		ZtAdmin ztAdmin=new ZtAdmin();
		ztAdmin.setId(adminid);
		ztAdmin=ztAdminService.get(ztAdmin);
		double commission=5000;
		int fans=1000;
		int nextSk=10;
		double myCommission=0;
		int myFans=0;
		int myNextSk=0;
		double rate=0d;
		
		if("1".equals(ztAdmin.getLevel())){//铜牌
		 commission =5000;//佣金
		 fans=1000;//粉丝
		 nextSk=10;//下级掌柜
		
		 myCommission =ztAdmin.getAmount();//自己的佣金
		
		 myFans=ztAdminService.getFansCount(ztAdmin);;//自己的粉丝
		 myNextSk=ztAdminService.getLevelFansCount(ztAdmin);//自己的下级掌柜
		
		double a=(myCommission/commission)*0.33;
		if(a>0.33){
			a=0.33;
		}
		double b=(myFans/1000d)*0.33;
		if(b>0.33){
			b=0.33;
		}
		double c=(myNextSk/10d)*0.34;
		if(c>0.34){
			c=0.34;
		}
		 rate=a+b+c; //进度
		 
		}
		
		Map m=new HashMap();
		m.put("commission",commission);
		m.put("fans",fans);
		m.put("nextSk",nextSk);
		m.put("rate",rate);
		m.put("myCommission",myCommission);
		m.put("myFans",myFans);
		m.put("myNextSk",myNextSk);
		
		
		res.setResult(200L);
		res.setData(m);
		Render.renderString(response, res);
	}
	
	
	/**
	 * 上传微信二维码
	 * @param request
	 * @param response
	 * @param model
	 */
	@ResponseBody
	@RequestMapping(value = "setWximg")
	public void setWximg(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String paramStr = CommonUtils.getParams(request);

		JSONObject jo = JSONObject.parseObject(paramStr);
		
		ResultObject res = new ResultObject();

		ZtAdmin smAdmin = new ZtAdmin();
		
		String adminid = jo.getString("adminid");
		String wximg = jo.getString("wximg");
		
		smAdmin.setId(adminid);
		smAdmin=ztAdminService.get(smAdmin);
		smAdmin.setWximg(wximg);
		ztAdminService.setNames();
		ztAdminService.save(smAdmin);
		res.setResult(200L);
		res.setData(smAdmin);
		Render.renderString(response, res);
	}
	
	@ResponseBody
	@RequestMapping(value = "withdraw")
	public void withdraw(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String paramStr = CommonUtils.getParams(request);

		JSONObject jo = JSONObject.parseObject(paramStr);
		
		ResultObject res = new ResultObject();

		ZtAdmin smAdmin = new ZtAdmin();
		
		String adminid = jo.getString("adminid");
		double withamount = Double.valueOf(jo.getString("withamount"));
		
		Date date=new Date();
		
		smAdmin.setId(adminid);
		smAdmin=ztAdminService.get(smAdmin);
		if(StringUtils.isBlank(smAdmin.getPaycode())){
			res.setResult(203L);//收款二维码未提交
			res.setMsg("收款二维码未提交");
			Render.renderString(response, res);
			return;
		}
		
		if(smAdmin.getCashAmount()<withamount){
			res.setResult(201L);//提现金额不足
			res.setMsg("提现金额不足");
			Render.renderString(response, res);
			return;
		}
		if(withamount<50){
			res.setResult(202L);//单次提现金额需大于50
			res.setMsg("单次提现金额需大于50");
			Render.renderString(response, res);
			return;
		}
		double a=smAdmin.getCashAmount()-withamount;
		smAdmin.setCashAmount(a);
		smAdmin.setAmount(smAdmin.getAmount()-withamount);
		ztAdminService.setNames();
		ztAdminService.save(smAdmin);
		
		ZtFinancial ztFinancial=new ZtFinancial();
		ztFinancial.setZtAdmin(smAdmin);
		ztFinancial.setContent("资金提现");
		ztFinancial.setPricestr("-￥"+withamount);
		ztFinancial.setPrice(withamount);
		ztFinancial.setType("4");
		ztFinancial.setCreateDate(date);
		ztFinancial.setStatus("0");
		ztFinancial.setUsername(smAdmin.getUsername());
		ztFinancial.setHeadimgurl(smAdmin.getHeadimgurl());
		
		ztAdminService.setNames();
		ztFinancialService.save(ztFinancial);
		
		
		ZtWithdraw ztWithdraw=new ZtWithdraw();
		ZtAdmin ztAdmin=new ZtAdmin();
		ztAdmin.setId(adminid);
		ztWithdraw.setZtAdmin(ztAdmin);
		ztWithdraw.setFinancialid(ztFinancial.getId());
		ztWithdraw.setIspay("0");
		ztWithdraw.setAmount(withamount);
		ztWithdraw.setCreateDate(date);
		
		ztWithdrawService.save(ztWithdraw);
		
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM");
		String dstr=format.format(date);
		int waCount=1;
		try{
		String withamountCount = JedisUtils.get("wa"+adminid+dstr);//提现次数
		if(StringUtils.isNotBlank(withamountCount)){
			waCount=Integer.valueOf(withamountCount)+1;
		}else{
			 waCount=1;
		}
		}catch(Exception ex){
			waCount=1;
		}
		
		JedisUtils.set("wa"+adminid+dstr, waCount+"", 0);
		
		res.setResult(200L);
		res.setData(smAdmin);
		Render.renderString(response, res);
	}
	
	
	@ResponseBody
	@RequestMapping(value = "getCardMem")
	public void getCardMem(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String paramStr = CommonUtils.getParams(request);

		JSONObject jo = JSONObject.parseObject(paramStr);
		
		ResultObject res = new ResultObject();

		ZtCardMem ztCardMem = new ZtCardMem();
		String adminid = jo.getString("adminid");
		ztCardMem.setAdminid(adminid);
		ztCardMem=ztCardMemService.getByAdminid(ztCardMem);
		if(ztCardMem==null){
			ztCardMem = new ZtCardMem();
		}
		
		if(ztCardMem!=null && StringUtils.isNotBlank(ztCardMem.getCardid())){
			ZtCard ztCard=new ZtCard();
			ztCard.setId(ztCardMem.getCardid());
			ztCard=ztCardService.get(ztCard);
			ztCardMem.setZtCard(ztCard);
		}
		
		res.setResult(200L);
		res.setData(ztCardMem);
		Render.renderString(response, res);
		
	}
	@ResponseBody
	@RequestMapping(value = "getAdminInfo")
	public void getAdminInfo(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String paramStr = CommonUtils.getParams(request);

		JSONObject jo = JSONObject.parseObject(paramStr);
		
		ResultObject res = new ResultObject();

		ZtAdmin smAdmin = new ZtAdmin();
		
		String adminid = jo.getString("adminid");
		
		smAdmin.setId(adminid);
		smAdmin=ztAdminService.get(smAdmin);
		
	
		if(StringUtils.isNotBlank(smAdmin.getCompany())&&!"0".equals(smAdmin.getCompany())){
			ZtCompany ztCompany=new ZtCompany();
			ztCompany.setCompany(smAdmin.getCompany());
			ztCompany=ztCompanyService.getByCompany(ztCompany);
			if(ztCompany!=null && StringUtils.isNotBlank(ztCompany.getId())){
				smAdmin.setCompany(ztCompany.getCompanyname());
			}
		}
		
		res.setResult(200L);
		res.setData(smAdmin);
		Render.renderString(response, res);
		
	}

	@ResponseBody
	@RequestMapping(value = "bindphone")
	public void addUser(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		String paramStr = CommonUtils.getParams(request);
		JSONObject jo = JSONObject.parseObject(paramStr);

		String ident = jo.getString("ident");
		String adminid = jo.getString("adminid");
	
		String phone = jo.getString("phone");
		ResultObject res = new ResultObject();
		int r = validate(phone);
		if (r == -1) {
			res.setResult(300L);
			res.setMsg("手机号为空");
			Render.renderString(response, res);
			return;

		} else if (r == -2) {
			res.setResult(300L);
			res.setMsg("手机号不符合规则");
			Render.renderString(response, res);
			return;

		} else if (r == -3) {// 有该用户
			res.setResult(300L);
			res.setMsg("手机号已存在");
			Render.renderString(response, res);
			return;
		} else {
		
		

		if (StringUtils.isBlank(ident)) {
			res.setResult(300L);
			res.setMsg("验证码不能为空");
			Render.renderString(response, res);
			return;
		}
		String redis_ident=JedisUtils.get(phone);
		
		if (redis_ident == null || !ident.equals(redis_ident)) {
			res.setResult(301L);
			res.setMsg("验证码错误或无效请重试");
			Render.renderString(response, res);
			return;
		}
		ZtAdmin ztAdmin=new ZtAdmin();
		ztAdmin.setPhone(phone);
		ztAdmin=ztAdminService.getByPhone(ztAdmin);
		if(ztAdmin==null){
			ZtAdmin ztAdmin1=new ZtAdmin();
			ztAdmin1.setId(adminid);
			ztAdmin1=ztAdminService.get(ztAdmin1);
			ztAdmin1.setPhone(phone);
			ztAdminService.update(ztAdmin1);
		}else if(StringUtil.isNotEmpty(ztAdmin.getOpenid())){
			res.setResult(301L);
			res.setMsg("该手机号码已经绑定");
			Render.renderString(response, res);
			return;
		}else{
			ZtAdmin ztAdmin1 = new ZtAdmin();
			ztAdmin1.setId(adminid);
			ztAdmin1=ztAdminService.get(ztAdmin1);
			ztAdmin1.setPhone(ztAdmin.getPhone());
			ztAdmin1.setName(ztAdmin.getName());
			ztAdmin1.setUsername(ztAdmin.getName());
			ztAdmin1.setSex(ztAdmin.getSex());
			ztAdmin1.setLevel(ztAdmin.getLevel());
			ztAdmin1.setMemtype(ztAdmin.getMemtype());
			ztAdmin1.setCashAmount(ztAdmin1.getCashAmount()+ztAdmin.getCashAmount());
			ztAdmin1.setAmount(ztAdmin1.getAmount()+ztAdmin.getAmount());
			ztAdmin1.setCompany(ztAdmin.getCompany());
			ztAdminService.mergeDelete(ztAdmin,ztAdmin1);
			ztFinancialService.updateAdminId(ztAdmin1.getId(),ztAdmin.getId());

		}


		res.setResult(200L);
		Render.renderString(response, res);
		}
	}

	protected int sendSms(String telephone_number, String sixSmsCode) {
		if(smsSendService==null){
			smsSendService=new SmsSendService();
		}
		SmsInfo info = smsSendService.send(telephone_number, sixSmsCode);
		if (info.getRetId() >= 0) {
			return 1;
		} else {
			return -1;
		}
	}
	
	
	
	/**
	 * 009.绑定发送验证码
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "sendSmsCode")
	public void sendSmsCode(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		response.setContentType("text/html; charset=utf-8");
		ResultObject res = new ResultObject();
		String paramStr = CommonUtils.getParams(request);
		JSONObject jo = JSONObject.parseObject(paramStr);

		String telephone_number = jo.getString("phone");
		

		try {
			// 验证手机号码合法性
			int r = validate(telephone_number);
			if (r == -1) {
				res.setResult(300L);
				res.setMsg("手机号为空");

			} else if (r == -2) {
				res.setResult(300L);
				res.setMsg("手机号不符合规则");

			}else {
				ZtAdmin ztAdmin=new ZtAdmin();
				ztAdmin.setPhone(telephone_number);
				ztAdmin=ztAdminService.getByPhone(ztAdmin);
				if(ztAdmin!=null){
					if(StringUtil.isNotEmpty(ztAdmin.getOpenid())){
						res.setResult(301L);
						res.setMsg("该手机号码已经绑定");
						Render.renderString(response, res);
						return;
					}
				}
				Random random = new Random();
				StringBuffer fourSmsCode = new StringBuffer()
						.append(random.nextInt(9)).append(random.nextInt(9))
						.append(random.nextInt(9)).append(random.nextInt(9));
				// 调用第三方平台发送短信

				// SendSmsResponse returns =SmsUtils.sendSms(telephone_number, fourSmsCode.toString());
						/*sendSms(telephone_number, new String(("验证码："
						+ new String(fourSmsCode) + "，如非本人操作，请忽略本短信【来来购来来回购】")));*/
				int returns = sendSms(telephone_number, new String(("您的手机验证码为"
						+ new String(fourSmsCode) + "，2分钟内有效。请不要把此验证码泄露给任何人。【企购购】")));

				if (returns == -1) {// 发送失败
					res.setResult(300L);
					res.setMsg("发送验证码失败,请重试");
				} else {
					res.setResult(200L);

					JedisUtils.set(telephone_number, fourSmsCode+"", 150);
			
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			res.setResult(300L);
			res.setMsg("发送验证码失败");
		}
		Render.renderString(response, res);
	}

	/**
	 * 验证手机号码是否11位，唯一性，是否已注册号码 复杂的可以用正则验证手机号码合法性
	 * 
	 * @param telephone_number
	 * @throws Exception
	 */
	protected int validate(String telephone_number) {
		if (telephone_number == null) {
			return -1;
		}
		if (telephone_number.length() != 11) {
			return -2;
		}
		return 1;

	}


	
	/**
	 * 图片上传 文章上传
	 * 
	 * @return
	 * @throws Exception
	 */
	// @ExcLoginInterceptor 自定义的拦截器注解
	@ResponseBody
	@RequestMapping(value = "/uploadImg")
	public void uploadImg(HttpServletRequest request,
			HttpServletResponse response) {
		ResultObject res = new ResultObject();

		long message = 200L;
		String schemeUrl = myProps.getServerPath()+"/wewoo";
		//request.getServerName() + 

		// 获取文件需要上传到的路径
		// String path = request.getServletContext().getRealPath("/upload")+"/";
		String path = request.getSession().getServletContext().getRealPath("")
				+ CommonPath.getDestFolder(request) + "/";
		
		System.out.println("----path====="+path);

		File dir = new File(path);

		if (!dir.exists()) {
			dir.mkdirs();
		}
		Map<String, String> map = new HashMap<String, String>();
		try {
			request.setCharacterEncoding("utf-8"); // 设置编码
			// 获得磁盘文件条目工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();

			// 如果没以下两行设置的话,上传大的文件会占用很多内存，
			// 设置暂时存放的存储室,这个存储室可以和最终存储文件的目录不同
			factory.setRepository(dir);
			// 设置缓存的大小，当上传文件的容量超过该缓存时，直接放到暂时存储室
			factory.setSizeThreshold(1024 * 1024);
			// 文件上传处理
			ServletFileUpload fileUpload = new ServletFileUpload(factory);
			List<FileItem> list = fileUpload.parseRequest(request);
			FileItem picture = null;
			System.out.println(list+"----fileUpload=============="+list.size());
			for (FileItem item : list) {
				// 获取表单的属性名字
				String name = item.getFieldName();
				// 如果获取的表单信息是普通的 文本 信息
				if (item.isFormField()) {
					// 获取用户具体输入的字符串
					String value = item.getString();
					map.put(name, value);
				} else {
					picture = item;
					// 根据当前时间生成图片的名称（需要自己封装写方法--当然也可以按自己的规则生成图片名称）

					String fileName = UUID.randomUUID().toString() + ".jpg";
					// /rtedu/resource/images/2018/1/25/d6281117-f19b-4d9b-a833-267e2447363e.jpg
					// 自定义上传图片的名字
					// String fileName = pictureName+".jpg";

					String destPath = path + fileName;
					// 此处可以保存与数据库，代码省略……

					// map.put(name, schemeUrl+destPath);

					// 真正写到磁盘上
					File file = new File(destPath);
					OutputStream out = new FileOutputStream(file);
					InputStream in = picture.getInputStream();
					int length = 0;
					byte[] buf = new byte[1024];
					// in.read(buf) 每次读到的数据存放在buf 数组中
					while ((length = in.read(buf)) != -1) {
						// 在buf数组中取出数据写到（输出流）磁盘上
						out.write(buf, 0, length);
					}
					message = 200L;
					in.close();
					out.close();
					System.out.println("--2228888----" + schemeUrl + destPath);
					String re = schemeUrl + destPath;
					res.setData(re.replaceAll(
							"/usr/local/tomcat8081/webapps/wewoo", ""));// 图片地址
					res.setResult(200L);

					Render.renderString(response, res);
					return;
				}
			}

		} catch (FileUploadException e1) {
			logger.error("", e1);
			message = 400L;
		} catch (Exception e) {
			logger.error("", e);
			message = 400L;
		}
		res.setResult(message);
		Render.renderString(response, res);
	}
	
	
	private void getQuan(String goodsid,ZtAdmin ztAdmin){
		ZtGoodsquan ztGoodsquan=new ZtGoodsquan();
		ztGoodsquan.setZtGoodsid(goodsid);
		List<ZtGoodsquan> ztQuanList = ztGoodsquanService.findList(ztGoodsquan);
		
		ZtGoods ztGoods=ztGoodsService.get(goodsid);
		
		String goodstemp=ztGoods.getGoodstemp();//0活动     1和2店铺。
		
		if("0".equals(goodstemp)){//活动
			ZtAdmin lastadmin=ztAdminService.get(ztAdmin.getLastadmin());
			String lastLevel=String.valueOf(Integer.valueOf(lastadmin.getLevel())+1);//0特级   1一级    2二级
		for(ZtGoodsquan zgq:ztQuanList){
					
			ZtQuan ztQuan=zgq.getZtQuan();//券
			if("2".equals(ztQuan.getType())){//如果是活动优惠券  
				if(lastLevel.equals(ztQuan.getLevelRange())){//1特级代理   2一级代理    3二级代理
					//ztQuan
					/*if("1".equals(lastLevel)){//如果是特级发的券
						ZtQuanself ztQuanself=new ZtQuanself();
						ztQuanself.setZtQuan(ztQuan);
						ztQuanself.setZtAdmin(ztAdmin);
						ztQuanself=ztQuanselfService.getByAdmin(ztQuanself);
						if(ztQuanself!=null){
							break;
						}else{
							ztQuanself=new ZtQuanself();
							ztQuanself.setZtQuan(ztQuan);
							ztQuanself.setZtAdmin(ztAdmin);
							ztQuanselfService.save(ztQuanself);
							break;
						}
					}*/
					ZtQuanself ztQuanself=new ZtQuanself();
					ztQuanself.setZtQuan(ztQuan);
					ztQuanself.setZtAdmin(ztAdmin);
					ztQuanself.setUsestatus("0");
					ztQuanself=ztQuanselfService.getByAdmin(ztQuanself);
					if(ztQuanself!=null){
						break;
					}else{
					
					ztQuanself=new ZtQuanself();
					ztQuanself.setZtQuan(ztQuan);
					ztQuanself.setZtAdmin(ztAdmin);
					ztQuanself.setCreateDate(new Date());
					ztQuanselfService.save(ztQuanself);
					break;
					}
					
				}
			}
			
		}
		}
	}
	
	
	@ResponseBody
	@RequestMapping(value = "getSimpleAdminInfo")
	public void getSimpleAdminInfo(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String paramStr = CommonUtils.getParams(request);

		JSONObject jo = JSONObject.parseObject(paramStr);
		
		ResultObject res = new ResultObject();

		ZtAdmin smAdmin = new ZtAdmin();
		
		String adminid = jo.getString("adminid");
		
		smAdmin.setId(adminid);
		smAdmin=ztAdminService.get(smAdmin);
		
		res.setResult(200L);
		res.setData(smAdmin);
		Render.renderString(response, res);
		
	}
	@Autowired
	GoodsTypeService goodsTypeService;
	@Autowired
	BrandService brandService;
	
	@Autowired
	ProductPoolUtils productPoolUtils;
	/**
	 * 获取商品
	 */
	@ResponseBody
	@RequestMapping(value = "product")
	public void product(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String paramStr = CommonUtils.getParams(request);
		JSONObject jo = JSONObject.parseObject(paramStr);
		String pageNum="1";
		if(jo.get("pageNum")!=null){
			pageNum=jo.get("pageNum").toString();
		}
		ZtGoods ztGoods=new ZtGoods();
		ztGoods.setPageNum((Integer.valueOf(pageNum)-1)*2000);
		List<ZtGoods> plp=ztGoodsService.findListPageNum(ztGoods);
		
			//List<ZtGoods> plp=ztGoodsService.findList(new ZtGoods());
			List<ZtGoods> plpList=new ArrayList<ZtGoods>();
			List<Brand> brandList=new ArrayList<Brand>();
			for(ZtGoods pp:plp){
				long sku=Long.valueOf(pp.getCode());
				
				 ztGoods=ProductPoolUtils.productDetail(sku);
				if(ztGoods==null){
					continue;
				}
				ztGoods.setGoodspool(pp.getPageNum()+"");
				ztGoods.setId(pp.getId());
				
				String type=ztGoods.getType();
				String typestr="";
				String typeName="";
				if(StringUtils.isNotBlank(type)){
					String[] typearr=type.split(";");
					if(typearr!=null && typearr.length>0){
 					for(String ty:typearr){
 						GoodsType goodsType=new GoodsType();
 						goodsType.setGoodsCode(ty);
 						goodsType=goodsTypeService.get(goodsType);
 						if(goodsType!=null){
 							typestr+=ty+",";
 							typeName+=goodsType.getName()+",";
 						}
 					}
 					if(StringUtils.isNotBlank(typestr)&& typestr.length()>1){
 					typestr=typestr.substring(0,typestr.length()-1);
 					}
 					if(StringUtils.isNotBlank(typeName)&& typeName.length()>1){
 					typeName=typeName.substring(0,typeName.length()-1);
 					}
					}
				}
				
				ztGoods.setType(typestr);
				ztGoods.setTypeName(typeName);
				
				Brand brand=new Brand();
				
				String bname=ztGoods.getBrandName();
				
				brand.setName(bname.trim());
				Brand ba=brandService.getByName(brand);
				if(ba==null || StringUtils.isBlank(ba.getId())){
					brand.setIsshow("1");
					brand.setCreateDate(new Date());
					brand.setType(typestr);
					brand.setTypeName(typeName);
					brandService.save(brand);
					ztGoods.setBrandid(brand.getId());

				}else{
					ztGoods.setBrandid(ba.getId());
				}
				
				plpList.add(ztGoods);
				
				if((plpList.size()%10)==0 && plpList.size()>1){
					ztAdminService.setNames();	
					ztGoodsService.batchUpdate(plpList);
					
					plpList.clear();
				}
				
			}
			
			if(plpList!=null && plpList.size()>0){
				ztAdminService.setNames();	
				ztGoodsService.batchUpdate(plpList);
			}
			
			if(brandList!=null && brandList.size()>0){
				ztAdminService.setNames();	
				brandService.batchSave(brandList);
			}
			
			ResultObject res = new ResultObject();
			res.setResult(200L);
			Render.renderString(response, res);
	}
	
	
	@ResponseBody
	@RequestMapping(value = "productimg")
	public void productimg(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String paramStr = CommonUtils.getParams(request);
		JSONObject jo = JSONObject.parseObject(paramStr);
		String pageNum="1";
		if(jo.get("pageNum")!=null){
			pageNum=jo.get("pageNum").toString();
		}
		ZtGoods ztGoods=new ZtGoods();
		ztGoods.setPageNum((Integer.valueOf(pageNum)-1)*2000);
		List<ZtGoods> plp=ztGoodsService.findListPageNum(ztGoods);
		//	List<ZtGoods> plp=ztGoodsService.findList(new ZtGoods());
			
			for(ZtGoods pp:plp){
				String sku=pp.getCode();
				
				String productimg=ProductPoolUtils.skuImageQuery(sku);
				pp.setContentimgs(productimg);
				
				ztGoodsService.saveContentimgs(pp);
			}
			
			ResultObject res = new ResultObject();
			res.setResult(200L);
			Render.renderString(response, res);
	}
	
	/**
	 * 1.1.21商品关联属性的商品集查询接口（查询SPU）
	 */
	@ResponseBody
	@RequestMapping(value = "shopinfo")
	public void shopinfo(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String paramStr = CommonUtils.getParams(request);
		JSONObject jo = JSONObject.parseObject(paramStr);
		String pageNum="1";
		if(jo.get("pageNum")!=null){
			pageNum=jo.get("pageNum").toString();
		}
		ZtGoods ztGoods=new ZtGoods();
		ztGoods.setPageNum((Integer.valueOf(pageNum)-1)*2000);
		List<ZtGoods> plp=ztGoodsService.findListPageNum(ztGoods);
		List<String>  goodspoolList=new ArrayList<String>();
			for(int i=0;i<plp.size();i++){
				JSONObject jj=new JSONObject();
				JSONArray ja=new JSONArray();
				
				String skus=plp.get(i).getCode();
				String goodspool=plp.get(i).getGoodspool();
				String id=plp.get(i).getId();
				//if(i%10!=0 || i==0){
					ja.add(skus);
					//goodspoolList.add(goodspool);
					
				//}else{
			
					jj.put("set",ja);//7670971
					productPoolUtils.shopinfo(jj.toJSONString(),goodspool,id);
					/*goodspoolList.clear();
					jj.clear();
					ja.clear();
					jj=new JSONObject();
					ja=new JSONArray();*/
					
				
			}
	
			/*if(ja!=null && ja.size()>0){
				jj.put("set",ja);
				productPoolUtils.shopinfo(jj.toJSONString(),goodspoolList);
			}*/
			
		
			ResultObject res = new ResultObject();
			res.setResult(200L);
			Render.renderString(response, res);
		
	}

	@ResponseBody
	@RequestMapping(value = "productSellPrice")
	public void productSellPrice(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String paramStr = CommonUtils.getParams(request);
		JSONObject jo = JSONObject.parseObject(paramStr);
		String pageNum="1";
		if(jo.get("pageNum")!=null){
			pageNum=jo.get("pageNum").toString();
		}
		ZtGoods ztGoods=new ZtGoods();
		ztGoods.setPageNum((Integer.valueOf(pageNum)-1)*2000);
		List<ZtGoods> plp=ztGoodsService.findListPageNum(ztGoods);
		
		List<ZtGoods> plpList=new ArrayList<ZtGoods>();
			
	//	List<ZtGoods> plp=ztGoodsService.findList(new ZtGoods());
		
		String skus="";
			for(int i=0;i<plp.size();i++){
			
				skus=plp.get(i).getCode();
				plpList.add(ProductPoolUtils.sellPrice(skus,plp.get(i)));
				if((i%100)==0 && i != 0){
					ztGoodsService.batchUpdatePrice(plpList);
					plpList.clear();
					plpList=new ArrayList<ZtGoods>();
				}
				
			}
			if(plpList!=null && plpList.size()>0){
			ztGoodsService.batchUpdatePrice(plpList);
			}
			ResultObject res = new ResultObject();
			res.setResult(200L);
			Render.renderString(response, res);
	}
	
	
	@ResponseBody
	@RequestMapping(value = "sk")
	public void sk(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String paramStr = CommonUtils.getParams(request);
		JSONObject jo = JSONObject.parseObject(paramStr);
		
		ZtGoods ztGoods=new ZtGoods();
		
		List<ZtGoods> plp=new ArrayList<ZtGoods>();
		ztGoods.setCode("2302819");
		ztGoods=ztGoodsService.getByCode(ztGoods);
		plp.add(ztGoods);
		List<ZtGoods> plpList=new ArrayList<ZtGoods>();
		
		String skus="";
			for(int i=0;i<plp.size();i++){
			
				skus=plp.get(i).getCode();
				plpList.add(ProductPoolUtils.sellPrice(skus,plp.get(i)));
				if((i%100)==0 && i != 0){
					ztGoodsService.batchUpdatePrice(plpList);
					plpList.clear();
					plpList=new ArrayList<ZtGoods>();
				}
				
			}
			if(plpList!=null && plpList.size()>0){
			ztGoodsService.batchUpdatePrice(plpList);
			}
			ResultObject res = new ResultObject();
			res.setResult(200L);
			Render.renderString(response, res);
	}

/*	@RequestMapping("cs")
	public void cs(String newAdmin,String admin){
				ztFinancialService.updateAdminId(newAdmin,admin);
	}*/
}